/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.farmcode.api.plugin.impl;

import com.farmcode.api.plugin.AuthenticationPlugin;
import com.farmcode.api.plugin.ConfigureException;
import com.farmcode.api.plugin.PluginImpl;
import com.farmcode.server.config.InitialContext;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

/**
 *
 * @author Oscar Ivan Prado
 */
public class DefaultAuthenticationPlugin extends PluginImpl implements AuthenticationPlugin {

    @Override
    public void configure() throws ConfigureException {
        Properties properties;
        try {
            properties = InitialContext.configure();
            configure(properties.getProperty(CONFIG));
        } catch (IOException ex) {
            Logger.getLogger(DefaultAuthenticationPlugin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    @Override
    public boolean autheticate(String userName, String password) {
        if (context == null) {
            return false;
        }
        //Algoritmo que permite autenticar contra directorio ldap
        if
        (
            context.getProperty(AuthenticationPlugin.AUTHENTICATION_TYPE) != null && 
            context.getProperty(AuthenticationPlugin.AUTHENTICATION_TYPE).toLowerCase().equals("ldap")
        ) {
            try {
                
                if(context.getProperty(DOMAIN) != null && !context.getProperty(DOMAIN).equals("")){
                    userName = context.getProperty(DOMAIN) + File.separatorChar + userName;
                }
                    
                context.put(Context.SECURITY_PRINCIPAL, userName); // specify the username ONLY to let Microsoft Happy
                context.put(Context.SECURITY_CREDENTIALS, password);   //the password

                DirContext ctx = new InitialDirContext(context);
                ctx.close();
                return true;
            } catch (NamingException ne) {
                
                return false;

            }
        }
        return true;
    }
}
